<template>
  <div>
    <div class="video" :class="{videosmall:smallMode,videoMax:maxMode}" id="ykf-video">
      <!-- <div class="top"> -->
      <div id="ykf-video-dragbar" class="ykf-video-dragbar" v-show="dragbarShow">
        <div class="minimg" v-show="!smallMode" @click="small"><i class="iconfont icon-zuixiaohua2 iconStyle"></i></div>
        <div class="middleImg" v-show="!smallMode" @click="max"><i class="iconfont icon-shipinzuidahua iconStyle"></i></div>
        <div class="close" v-show="!smallMode" @click="closeFun('close')"><i class="iconfont icon-guanbi2 iconStyle"></i></div>
      </div>
      <img src="../../../assets/img/big.png" class="maximg" v-show="smallMode" @click="normalMode">
      <!-- </div> -->
      <div id="meet"></div>
      <!-- <iframe :src="url" v-if="rtcUrl !== ''" frameborder="0" width="100%" height="100%" allow="microphone; camera"></iframe> -->
    </div>
  </div>
</template>
<script>
  import * as types from '@/store/modules/webchat/mutation-types.js'
  import * as uuid from 'uuid'
  import * as recorderObj from '@/utils/recorder.js'
  import '@/utils/external_api'
  let tWidth, tHeight
  window.onresize = function () {
    tWidth = document.body.clientWidth
    tHeight = document.body.clientHeight
  }
  export default ({
    data () {
      return {
        api: null,
        room: "test romm",
        username: "rabie",
        swit: true,
        smallMode: false,
        maxMode: false,
        dragbarShow: true,
        params: {
          left: 0,
          top: 0,
          currentX: 0,
          currentY: 0,
          flag: false
        },
        dragWidth: 0,
        dragHeight: 0,
        rtcUrl: '',
        videoRecord: false,
        isCustormJoin: false
      }
    },
    computed: {
      Username () {
        return this.$store.state.webchat.videoChatData.videoUsername
      },
      // url () {
        // return this.rtcUrl + '/?token=' + this.$store.state.webchat.videoChatData.videoToken +
        //   '&role=2&Username=' + this.Username + '&kefuid=' + this.$store.state.session.user._id +
        //   '&record=' + this.videoRecord + '&videoSource=' + this.$store.state.webchat.videoChatData.videoSource +
        //   '&hideCamera=' + this.$store.state.webchat.hideVideoCamera
        // return 'https://jitsi.rtctest.7moor.com/12345'
      // },
      sessionId () {
        return this.$store.state.webchat.videoChatData.videoSessionid
      },
      roomId () {
        return this.$store.state.webchat.videoChatData.roomId
      },
      password () {
        return this.$store.state.webchat.videoChatData.password
      },
      refreshFlag () {
        return this.$store.state.webchat.videoChatData.refreshFlag
      },
      videoInvitedRoomId () {
        return this.$store.state.webchat.videoInvitedData.roomId || ''
      },
      avatarUrl () {
        let tempUrl = this.$store.state.session.user.im_icon ? this.$store.state.session.user.im_icon + '?imageView2/1/w/200/h/200' : ''
        return tempUrl
      }
    },
    watch: {
      refreshFlag () {
        this.closeFun('refuse')
      }
    },
    methods: {
      closeFun (status) {
        let videoMsg = {
          videoSessionid: '',
          videoToken: '',
          videoUsername: '',
          videoSource: '',
          roomId: '',
          password: ''
        }
        var statusNew = status
        // var videoPeople = this.api.getNumberOfParticipants()
        if (status === 'close') {
          statusNew = this.isCustormJoin ? 'hangup' : 'cancel'
        }
        var originator = this.$store.state.webchat.invitePersonnel || 'agent'
        if (statusNew) {
          // 自己主动挂断
          let sendcancelMsg = {
            _id: this.sessionId,
            operation: statusNew,
            originator: originator
          }
          // sendcancelMsg.operation = this.isCustormJoin ? 'hangup' : 'cancel'
          this.$store.dispatch('cancelVideoInvite', sendcancelMsg)
        } else {
          let sendHangupMsg = {
            _id: this.sessionId,
            operation: 'refuse',
            originator: originator
          }
          this.$store.dispatch('rejectVideoInvite', sendHangupMsg)
        }
        this.$store.commit(types.UPDATE_VIDEO_CHATDATA, videoMsg)
        let videoIniteMsg = {
          videoInviteSessionid: '',
          // videoInviteToken: '',
          platform: '',
          roomId: '',
          password: ''
        }
        // recorderObj.stop();
        this.$store.commit(types.UPDATE_VIDEO_INVITE_DATA, videoIniteMsg)
        // this.api.executeCommand('hangup')
        this.$store.commit(types.UPDATE_VIDEO_CHAT_STATUS, false)
      },
      getMsgFromChildFrame (b) {
        // console.log(new Date().getTime())
        var originator = this.$store.state.webchat.invitePersonnel || 'agent'
        if (b.data === 'UserHangup') {
          this.$store.commit(types.UPDATE_VIDEO_CHAT_STATUS, false)
          let videoMsg = {
            videoSessionid: '',
            videoToken: '',
            videoUsername: '',
            videoSource: ''
          }
          this.$store.commit(types.UPDATE_VIDEO_CHATDATA, videoMsg)
        }
        if (b.data === 'UserCancel') {
          let msg = {
            _id: this.sessionId,
            operation: 'cancel',
            originator: originator
          }
          this.$store.dispatch('cancelVideoInvite', msg)
        }
        if (typeof b.data === 'string' && b.data.indexOf('notSupport') !== -1) {
          let videoSource = b.data.substring('notSupport'.length)
          this.$store.commit(types.UPDATE_VIDEO_CHAT_STATUS, false)
          if (videoSource === 'invited') {
            let msg = {
              _id: this.sessionId,
              operation: 'refuse',
              originator: originator
            }
            this.$store.dispatch('rejectVideoInvite', msg)
            let videomsg = {
              videoSessionid: '',
              videoToken: '',
              videoUsername: '',
              videoSource: ''
            }
            this.$store.commit(types.UPDATE_VIDEO_CHATDATA, videomsg)
          } else if (videoSource === 'initiative') {
            let msg = {
              _id: this.sessionId,
              operation: 'cancel',
              originator: originator
            }
            this.$store.dispatch('cancelVideoInvite', msg)
          }
        }
        if (typeof b.data === 'string' && b.data.indexOf('lostConnect') !== -1) {
          let videoStatus = b.data.substring('lostConnect'.length)
          if (videoStatus === '0') {
            // 会话邀请，对方未进入，失去连接
            let msg = {
              _id: this.sessionId,
              operation: 'cancel',
              originator: originator
            }
            this.$store.dispatch('cancelVideoInvite', msg)
            this.$message.error(this.$t('webchat.VideoLostConnect'))
          } else if (videoStatus === '1') {
            // 正常通话中失去连接
            this.$store.commit(types.UPDATE_VIDEO_CHAT_STATUS, false)
            let videoMsg = {
              videoSessionid: '',
              videoToken: '',
              videoUsername: '',
              videoSource: ''
            }
            this.$store.commit(types.UPDATE_VIDEO_CHATDATA, videoMsg)
            this.$message.error(this.$t('webchat.VideoLostConnect'))
          }
        }
        if (b.data === 'location') {
          if (this.$route.path.substring('/index/webchat/webchat_todo/'.length) === this.sessionId) {
            this.$nextTick(function () {
              document.getElementsByClassName('send_msg_textarea')[0].focus()
            })
          } else {
            this.$router.push({path: '/index/webchat/webchat_todo/' + this.sessionId})
          }
        }
//        if (b.data === 'UserHangup' || b.data === 'UserCancel' || b.data === 'notSupport') {
//          window.removeEventListener('message', this.getMsgFromChildFrame)
//        }
      },
      small () {
        let iframe = document.getElementById('ykf-video').getElementsByTagName('iframe')[0].contentWindow
        let Video = document.getElementById('ykf-video')
        Video.style.left = '70%'
        Video.style.top = '44%'
        iframe.postMessage('smallMode', '*')
        this.smallMode = true
        this.maxMode = false
      },
      max () {
        let iframe = document.getElementById('ykf-video').getElementsByTagName('iframe')[0].contentWindow
        let Video = document.getElementById('ykf-video')
        if (this.maxMode) {
          Video.style.left = '28%'
          Video.style.top = '20%'
          this.maxMode = false
        } else {
          Video.style.left = '0'
          Video.style.top = '0'
          this.maxMode = true
        }
        iframe.postMessage('smallMode', '*')
        this.smallMode = false
      },
      normalMode () {
        let iframe = document.getElementById('ykf-video').getElementsByTagName('iframe')[0].contentWindow
        let Video = document.getElementById('ykf-video')
        Video.style.left = '28%'
        Video.style.top = '20%'
        iframe.postMessage('bigMode', '*')
        this.smallMode = false
        this.maxMode = false
      },
      getCss (o, key) {
        return o[key]
      },
      startDrag (bar, target, self, callback) {
        bar.onmousedown = function (event) {
          console.log(self.getCss(target, 'offsetLeft'))
          event.preventDefault()
          if (self.getCss(target, 'offsetLeft') !== 'auto') {
            self.params.left = self.getCss(target, 'offsetLeft')
          }
          if (self.getCss(target, 'offsetTop') !== 'auto') {
            self.params.top = self.getCss(target, 'offsetTop')
          }
          self.params.flag = true
          if (!event) {
            event = window.event
            bar.onselectstart = function () {
              return false
            }
          }
          let e = event
          self.params.currentX = e.clientX
          self.params.currentY = e.clientY < 0 ? 0 : e.clientY
        }
        target.onmouseup = function () {
          self.params.flag = false
          if (self.getCss(target, 'offsetLeft') !== 'auto') {
            self.params.left = self.getCss(target, 'offsetLeft')
          }
          if (self.getCss(target, 'offsetTop') !== 'auto') {
            self.params.top = self.getCss(target, 'offsetTop')
          }
        }
        target.onmousemove = function (event) {
          let e = window.event
          let nowX = e.clientX
          let nowY = e.clientY
          let disX = 0
          let disY = 0
          if (self.params.flag) {
            disX = nowX - self.params.currentX
            disY = nowY - self.params.currentY
            // 判断上下左右的极限位置
            let limitLeft = (parseInt(self.params.left) + disX) > (tWidth - 50) ? (tWidth - 50) : (parseInt(self.params.left) + disX) < (100 - self.dragWidth) ? 100 - self.dragWidth : parseInt(self.params.left) + disX
            let limitTop = (parseInt(self.params.top) + disY) > (tHeight - 34) ? (tHeight - 34) : (parseInt(self.params.top) + disY) < 0 ? 0 : parseInt(self.params.top) + disY
            target.style.left = limitLeft + 'px'
            target.style.top = limitTop + 'px'
          }
          if (typeof callback === 'function') {
            callback(parseInt(self.params.left) + disX, parseInt(self.params.top) + disY)
          }
        }
      },
      dragBarOver (self) {
        let oContent = document.getElementById('ykf-video')
        oContent.onmouseover = function () {
          console.log('鼠标移入')
          self.dragbarShow = true
        }
        oContent.onmouseout = function () {
          console.log('鼠标移出')
          self.dragbarShow = false
        }
      },
    startConference() {
      var hideVideoCamera = this.$store.state.webchat.hideVideoCamera
      var _this = this
      try {
        const domain = 'kfvideo.7moor.com'
        // const domain = 'jitsi.rtctest.7moor.com'
        /**
          *  
          * startWithAudioMuted true代表进入视频会议关闭麦克风
            startWithVideoMuted true代表 进入视频会议关闭摄像头
            transcribingEnabled 去掉语音转字幕按钮
            requireDisplayName 去掉进入会议需要输入用户名
            enableWelcomePage 开启欢迎页
            enableClosePage 不开启关闭页
            resolution 分辨率
            constraints 最大 最小 最理想

            上述设置在new JitsiMeetExternalAPI时候有效
          * 
          */
        var configOverwrite = {
          startWithAudioMuted: false,
          startWithVideoMuted: hideVideoCamera,
          transcribingEnabled: false,
          requireDisplayName: false,
          enableWelcomePage: true,
          enableClosePage: false,
          resolution: 720,
          constraints: {
            video: {
                height: {
                    ideal: 720,
                    max: 720,
                    min: 180
                },
                width: {
                    ideal: 1280,
                    max: 1280,
                    min: 320
                }
            },
            p2p: {
              enabled: false,  // 开启p2p 客户端直连方案，有可能以后会关闭 设置为false流量从服务器中转
              // stunServers: [
                // { urls: 'stun:jitsi.rtctest.7moor.com:4446' }
              // ],
              preferH264: true, // 开启H264支持
              disableH264: false,
              useStunTurn: false, // use XEP-0215 to fetch STUN and TURN servers for the P2P connection  p2p直连需要做sturn和coturn NAT穿越
            },
            useStunTurn: true, // use XEP-0215 to fetch TURN servers for the JVB connection
            useTurnUdp: false,
          },
          disableRemoteMute: true,
          disable1On1Mode: true,
          disableRemoteMute: true,
        }
        const options = {
          roomName: this.room,
          height: "100%",
          parentNode: document.querySelector("#meet"),
          interfaceConfigOverwrite: { //界面按钮
            TOOLBAR_BUTTONS: [
              'microphone', 'camera', 'desktop', 'fullscreen',
              'fodeviceselection', 'hangup', 'settings',
              'videoquality'
            ],
            SETTINGS_SECTIONS:  ['devices', 'language'], //设置按钮
          },
          configOverwrite: configOverwrite
        }
        if ( recorderObj.checkCodecsSupported() ){
          //开始录制
          // recorderObj.recordStart();
          // 初始化
          this.api = new JitsiMeetExternalAPI(domain, options)
          // 创建房间后为房间设置密码，没有密码加入不了房间
          // 房间号和密码通过云客服的API推送给另一端
          this.api.executeCommand('subject', ' ')
          this.api.executeCommand("avatarUrl", ' ')   // 设置头像为空
          _this.api.executeCommand("displayName", '座席') // 设置名称
          this.api.addEventListener('participantRoleChanged', function(event) {
            if (event.role === "moderator") {
              _this.api.executeCommand('password', _this.password);
            }
          });


          // 另一端收到通过云客服API收到密码后
          // 调用此API输入密码
          this.api.on('passwordRequired', function () {
            _this.api.executeCommand('password', _this.password);
          });
          
          this.api.addEventListener("videoConferenceJoined", (event) => {
            _this.api.executeCommand('subject', ' ')      // 房间名称设置为空
            if (_this.avatarUrl) {
              _this.api.executeCommand("avatarUrl", _this.avatarUrl)    // 设置头像
            } else {
              _this.api.executeCommand("avatarUrl", ' ')    // 设置头像
            }
          })
          this.api.addEventListener("participantJoined", (event) => {
            if (event && event.id) {
              this.isCustormJoin = true
            }
          })
          this.api.addEventListener('readyToClose', (event) => {
            // 自己挂断事件
            // console.log("视频事件日志");
            // console.log("自己挂断事件");
            _this.closeFun('close')
          })
          this.api.addEventListener("participantLeft", (event) => {
            // 对方挂断事件
            // console.log("视频事件日志");
            // console.log("对方挂断事件");
          })
        } else {
            alert("请升级你的浏览器！");
        }
      } catch (error) {
        console.error("Failed to load Jitsi API", error)
      }
    },
    openRoom() {
        if (window.JitsiMeetExternalAPI) {
          this.startConference();
        }
      }
    },
    mounted () {
      let oContent = document.getElementById('ykf-video')
      let oBar = document.getElementById('ykf-video-dragbar')
      this.dragBarOver(this)
      this.startDrag(oBar, oContent, this)
      this.dragWidth = oContent.clientWidth
      this.dragHeight = oContent.clientHeight
      tWidth = document.body.clientWidth
      tHeight = document.body.clientHeight
      // if (window.addEventListener) {
      //   window.addEventListener('message', this.getMsgFromChildFrame)
      // } else {
      //   window.attachEvent('onmessage', this.getMsgFromChildFrame)
      // }
      if (this.videoInvitedRoomId && this.videoInvitedRoomId !== '') {
        this.room = this.videoInvitedRoomId
      }  else {
        this.room = this.roomId
      }
      this.openRoom()
    },
    beforeMount () {
      this.$store.dispatch('getCache', {type: 'rtcUrl'}).then(() => {
//        this.rtcUrl = this.$store.state.session.dicMap.rtcUrl
        this.rtcUrl = this.$getCache('rtcUrl')
      })
      this.$store.dispatch('getCache', {type: 'channelGlobalSet'}).then((channelGlobalSet) => {
        if (channelGlobalSet.videorecord === '1') {
          this.videoRecord = true
        } else {
          this.videoRecord = false
        }
      })
    },
    beforeDestroy () {
      // this.closeFun()
      this.api.removeEventListener(['videoConferenceJoined', 'videoConferenceLeft'])
      // window.removeEventListener('message', this.getMsgFromChildFrame)
      this.api.dispose()
    }
  })
</script>
<style lang='stylus' scoped type="text/stylus">
  @import "../../../assets/common.styl"
  #meet
    width 100%
    height 100%
  .iconStyle
    color #fff
    display inline-block
    margin-top  2px  
  .top
    height 50px
    background #f2f2f2
  .video
    position: absolute;
    left: 28%;
    top: 20%;
    width: 700px;
    height: 500px;
    z-index: 30000;
    overflow: hidden;
    background: $cf-white;
    border-radius: 6px;
    box-shadow: 0 0 3px 2px rgba(53, 53, 53, 0.1);
    border-top-width: 1px;
    border-right-width: 1px;
    border-left-width: 1px;
    border-style: solid solid none;
    border-top-color: #19CAA6;
    border-right-color: #19CAA6;
    border-left-color: #19CAA6;
    .ykf-video-dragbar
      width: 100%;
      height: 36px;
      position: absolute;
      background-color: rgba(255,255,255,0.5);
      cursor: move;
    .close
      position: absolute;
      right: 14px;
      top: 22%;
      width: 20px;
      height: 20px;
      opacity: 0.5;
      background-color: #000;
      border-radius: 50%;
      text-align: center;
      cursor: pointer;
    .middleImg
      position: absolute;
      right: 42px;
      top: 22%;
      width: 20px;
      height: 20px;
      opacity: 0.5;
      background-color: #000;
      border-radius: 50%;
      text-align: center;
      cursor: pointer;
    .minimg
      position: absolute;
      right: 70px;
      top: 22%;
      width: 20px;
      height: 20px;
      background-color: #000;
      opacity: 0.5;
      border-radius: 50%;
      text-align: center;
      cursor: pointer;
      img
        width: 25px;
        vertical-align: middle;
    .minimg:after
      content: '';
      display: inline-block;
      width: 0;
      height: 100%;
      vertical-align: middle;
    .maximg
      position: absolute;
      right: 2%;
      top: 2%;
      width: 17px;
      height: 17px;
      cursor: pointer;
  .videosmall
    width 350px
    height 250px
    .top
      height 20px
  .videoMax
    width 100vw
    height 100vh
    .top
      height 20px
</style>
